package com.kalvan.web.feign;

import cn.hutool.core.util.ReflectUtil;
import com.kalvan.client.system.SystemUtil;
import com.kalvan.web.feign.cache.FeignCacheService;
import feign.Client;
import feign.Request;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * Mock Feign client
 * prod环境下不生效
 *
 * @author chenliang
 */
@Slf4j
public class FeignMockClient extends LoadBalancerFeignClient implements InitializingBean {
    public static final String PROD = "prod";
    Default httpClient = new Default(null, null);
    @Resource
    private FeignCacheService feignCacheService;

    public FeignMockClient(CachingSpringLoadBalancerFactory cachingFactory, SpringClientFactory clientFactory) {
        super(new Client.Default(null, null), cachingFactory,
                clientFactory);
        log.info("init FeignMockClient...");
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        if (!PROD.equalsIgnoreCase(SystemUtil.constants.getProfile())) {
            String url = request.url();
            String mockUrl = feignCacheService.getMockUrl(url);
            if (StringUtils.isNotBlank(mockUrl)) {
                log.info("mock请求:{} -> {}", url, mockUrl);
                ReflectUtil.setFieldValue(request, "url", mockUrl);
                //直接使用http请求
                return httpClient.execute(request, options);
            }
        }
        //使用lb请求
        return super.execute(request, options);
    }

    @Override
    public void afterPropertiesSet() {
    }
}
